import axios from 'axios'

export default options => {
  const { axiosRequestConfig, tokenKey } = options

  const instance = axios.create(axiosRequestConfig)

  instance.interceptors.request.use(
    config => {
      const { successMsg, errorMsg, showLoading, needLogin } = config
      const token = options.getToken ? options.getToken() : null

      // 需要登录
      if (needLogin && !token) return options.goLogin()

      // token
      if (tokenKey) config.headers[tokenKey] = token

      // 响应在200毫秒内不显示loading
      setTimeout(() => {
        if (showLoading && !config.done) options.showLoading(config)
      }, 150)

      config.onSuccess = res => {
        if (showLoading && config.loading) options.closeLoading(config)
        if (successMsg) options.message('success', typeof successMsg == 'string' ? successMsg : res.msg)
        return Promise.resolve(res)
      }

      config.onFail = (error, res) => {
        if (showLoading) options.closeLoading(config)
        if (errorMsg) options.message('error', error)
        return Promise.reject([error, res])
      }

      return config
    },
    error => {
      options.message('error', '请求超时!')
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use(
    response => {
      const { config } = response

      config.done = true

      if (config.showLoading) options.closeLoading(config)

      const { status, data } = response

      if (status && status == 200) {
        // 如果是文件流直接成功返回
        if (data instanceof Blob) {
          return config.onSuccess(response)
        }

        if (data.status == 200) {
          return config.onSuccess(data.data)
        } else {
          if (data.code == 401 || data.code == 402) {
            return options.goLogin(data.data)
          }

          return config.onFail(data.message, data)
        }
      } else {
        return config.onFail('数据解析异常', data)
      }
    },
    error => {
      const { config, response } = error

      if (config) config.done = true

      if (response) {
        let message

        if (response.data && response.data.message) {
          message = response.data.message
        } else if (response.status == 504 || response.status == 404) {
          message = '服务器异常'
        } else if (response.status == 403) {
          message = '权限不足,请联系管理员!'
        } else {
          message = '未知错误!'
        }

        return config.onFail(message, response.data)
      } else {
        if (config) {
          return config.onFail(error.message, error)
        } else {
          return Promise.reject([error.message, error])
        }
      }
    }
  )

  return instance
}
